package o;

import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import java.io.IOException;
import java.io.OutputStream;

public final class sj extends OutputStream {
    private int ˊ;
    private ud ˋ;
    @NonNull
    private final OutputStream ˎ;
    private byte[] ˏ;

    public sj(@NonNull OutputStream outputStream, @NonNull ud udVar) {
        this(outputStream, udVar, WXMediaMessage.THUMB_LENGTH_LIMIT);
    }

    @VisibleForTesting
    sj(@NonNull OutputStream outputStream, ud udVar, int i) {
        this.ˎ = outputStream;
        this.ˋ = udVar;
        this.ˏ = (byte[]) udVar.ॱ(i, byte[].class);
    }

    public void write(int i) throws IOException {
        byte[] bArr = this.ˏ;
        int i2 = this.ˊ;
        this.ˊ = i2 + 1;
        bArr[i2] = (byte) i;
        ˋ();
    }

    public void write(@NonNull byte[] bArr) throws IOException {
        write(bArr, 0, bArr.length);
    }

    public void write(@NonNull byte[] bArr, int i, int i2) throws IOException {
        int i3 = 0;
        do {
            int i4 = i2 - i3;
            int i5 = i + i3;
            if (this.ˊ != 0 || i4 < this.ˏ.length) {
                i4 = Math.min(i4, this.ˏ.length - this.ˊ);
                System.arraycopy(bArr, i5, this.ˏ, this.ˊ, i4);
                this.ˊ += i4;
                i3 += i4;
                ˋ();
            } else {
                this.ˎ.write(bArr, i5, i4);
                return;
            }
        } while (i3 < i2);
    }

    public void flush() throws IOException {
        ॱ();
        this.ˎ.flush();
    }

    private void ॱ() throws IOException {
        if (this.ˊ > 0) {
            this.ˎ.write(this.ˏ, 0, this.ˊ);
            this.ˊ = 0;
        }
    }

    private void ˋ() throws IOException {
        if (this.ˊ == this.ˏ.length) {
            ॱ();
        }
    }

    public void close() throws IOException {
        try {
            flush();
            ˏ();
        } finally {
            this.ˎ.close();
        }
    }

    private void ˏ() {
        if (this.ˏ != null) {
            this.ˋ.ˊ(this.ˏ);
            this.ˏ = null;
        }
    }
}
